<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>系统用户</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="filterName" @input="inputAlter" placeholder="用户名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">
          搜索
        </el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleCreate()">
          添加用户
        </el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="
      dataList.slice(
        (this.pageparm.currentPage - 1) * this.pageparm.pageSize,
        this.pageparm.currentPage * this.pageparm.pageSize
      )
    " highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%">
      <el-table-column sortable prop="name" label="用户名称"> </el-table-column>
      <el-table-column sortable prop="group" label="用户角色" :formatter="formatterGroup"> </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 新建页面 -->
    <el-dialog title="添加用户" :visible.sync="createDialogVisible" width="33%" @click="closeCreateDialog">
      <el-form label-width="120px" :model="userForm" :rules="createRules" ref="userForm" class="tmpl-create">
        <el-form-item label="用户名" prop="name" class="name-input">
          <el-input size="small" v-model="userForm.name" auto-complete="off" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input size="small" v-model="userForm.password" auto-complete="off" placeholder="请输入密码" show-password>
          </el-input>
        </el-form-item>
        <el-form-item label="角色" prop="group">
          <el-select v-model="userForm.group" placeholder="请选择用户角色">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeCreateDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="submitCreate('userForm')">
          创建
        </el-button>
      </div>
    </el-dialog>
    <!-- 编辑页面 -->
    <el-dialog title="编辑用户信息" :visible.sync="editDialogVisible" width="33%" @click="closeEditDialog">
      <el-form label-width="120px" :model="editRow" :rules="editRules" ref="editRow" class="tmpl-edit">
        <el-form-item label="用户名" prop="name" class="name-input">
          <el-input size="small" v-model="editRow.name" placeholder="用户名" :disabled="true">
          </el-input>
        </el-form-item>
        <el-form-item label="角色" prop="group">
          <el-select v-model="editRow.group" placeholder="请选择用户角色">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" @click="submitEdit('editRow')">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from "../../components/Pagination";
  export default {
    data() {
      return {
        loading: false, //是显示加载
        editDialogVisible: false, //控制编辑页面显示与隐藏
        createDialogVisible: false,
        filterName: "",
        userForm: {
          name: "",
          password: "",
          group: "",
        },
        editRow: {
          name: "",
          group: "",
        },
        options: [
          {
            value: "user@group",
            label: "学生",
          },
          {
            value: "admin@group",
            label: "老师",
          },
        ],
        // rules表单验证
        createRules: {
          name: [
            { required: true, message: "用户名不能为空", trigger: "blur" },
          ],
          password: [
            { required: true, message: "密码不能为空", trigger: "blur" },
          ],
          group: [
            { required: true, message: "角色不能为空", trigger: "blur" },
          ],
        },
        editRules: {
          name: [
            { required: true, message: "用户名不能为空", trigger: "blur" },
          ],
          group: [
            { required: true, message: "角色不能为空", trigger: "blur" },
          ],
        },
        dataList: [], //用户数据
        // 分页参数
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10,
        },
      };
    },
    // 注册组件
    components: {
      Pagination,
    },
    /**
     * 创建完毕
     */
    created() {
      // 获取数据列表
      this.getDataList();
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      // 获取数据方法
      getDataList() {
        this.$axios.get("/users/").then((res) => {
          console.log(res);
          this.dataList = res.data.data.filter((item) => item.name !== "atlas");
          this.pageparm.total = this.dataList.length;
        });
      },
      // 分页插件事件
      callFather(parm) {
        this.pageparm.currentPage = parm.currentPage;
        this.pageparm.pageSize = parm.pageSize;
      },
      //新建页面
      handleCreate: function () {
        this.createDialogVisible = true;
        this.userForm.name = "";
        this.userForm.password = "";
        this.userForm.group = "";
      },
      // 创建页面保存
      submitCreate(formData) {
        this.$refs[formData].validate((valid) => {
          if (valid) {
            this.$axios
              .post("/users/create/", this.userForm)
              .then((res) => {
                this.createDialogVisible = false;
                this.loading = false;
                this.getDataList();
              })
              .catch((err) => {
                this.createDialogVisible = false;
                this.loading = false;
                this.$message.error("创建用户失败，请稍后再试！");
              });
          } else {
            return false;
          }
        });
      },
      //显示编辑界面
      handleEdit: function (index, row) {
        this.editDialogVisible = true;
        this.editRow.name = row.name
        this.editRow.group = row.group;
      },
      // 编辑页面保存
      submitEdit(editData) {
        this.$refs[editData].validate((valid) => {
          if (valid) {
            this.loading = true;
            this.$axios
              .post("/users/info/" + this.editRow.name + "/", this.editRow)
              .then((res) => {
                console.log("🚀 ~ file: user.vue ~ line 221 ~ .then ~ res", res)
                this.editDialogVisible = false;
                this.loading = false;
                this.getDataList();
              })
              .catch((err) => {
                this.editDialogVisible = false;
                this.loading = false;
                this.$message.error("编辑用户角色失败，请稍后再试！");
              });
          } else {
            return false;
          }
        });
      },
      // 删除用户
      deleteUser(index, row) {
        this.$confirm("确定要删除吗?", "信息", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$axios
              .post("/users/delete/" + row.name + "/")
              .then((res) => {
                this.$message({
                  type: "success",
                  message: "用户已删除!",
                });
                this.getDataList();
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      },
      // 关闭新建对话框
      closeCreateDialog() {
        this.createDialogVisible = false;
      },
      // 关闭编辑弹出框
      closeEditDialog() {
        this.editDialogVisible = false;
      },
      // 输入框内容改变
      inputAlter() {
        if (this.filterName == "") {
          this.getDataList();
        } else {
          this.dataList = this.dataList.filter((value) => {
            return value.name.match(this.filterName);
          });
          this.pageparm.total = this.dataList.length;
        }
      },
      // 搜索事件
      search() {
        this.dataList = this.dataList.filter((value) => {
          return value.name.match(this.filterName);
        });
        this.pageparm.total = this.dataList.length;
      },
      formatterGroup(row, col) {
        switch (row.group) {
          case "admin@group":
            return "教师";
            break;
          case "user@group":
            return "学生";
          default:
            break;
        }
      }
    },
  };
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }

  .userRole {
    width: 100%;
  }

  .tmpl-create {
    margin-right: 60px;
  }

  .tmpl-edit {
    margin-right: 60px;
  }
</style>